<template >
<view class="container">
   
    <div class="page">
    <div class="page__hd"  :hidden="!loginAttr">
      <div class="page__title" @click="clieckMe" id="clikcMme">点我，查看快速下单示例</div>
      <div class="page__desc" :hidden="lookMe">
        <p>单号：12</p>
        <p>店名：裕轩湛江鸭仔饭</p>
        <p>地址：望岗地铁站嘉禾村大道地铁站边</p>
        <p>需求：昌顺香米-5-包-115元,大豆油-2-桶-180元</p>
        <p>老板：13723453927-张</p>
        <p>业务：吴岳-13928926082</p>
      </div>
    </div>

    <!-- <div class="weui-cells__title">请输入下单内容</div> -->
      <div class="weui-cells weui-cells_after-title" :hidden="!loginAttr">
        <div class="weui-cell">
          <div class="weui-cell__bd">
            <textarea class="" placeholder="请输入下单内容" style="height: 9em;width:360px" v-model="orderContent"/>
            <!-- <div class="weui-textarea-counter">0/200</div> -->
          </div>
        </div>
      </div>

      <div class="button-sp-area" @click="searchAddress" :hidden="!loginAttr">
          <button class="weui-btn" :hidden="!showMap" @click="searchAddress" type="primary" plain="true">选择客户位置</button>
          <view class="brand" :hidden="showMap">
           <img :src="mapImag"  id="photo">
        </view>
      </div>
    </div>
     <div class="attr-pop-box_login" :hidden="loginAttr">
   
        <div class="attr-pop_login">
          <img class="icon" src="/static/images/ic_menu_me_pressed.png"/>
          <button v-if="canIUse" open-type="getUserInfo" @getuserinfo="goLogin" class="goLoginBtn" >点击，授权登录~</button>
        </div>
      </div>
    <div class="button-sp-area"  :hidden="showMap">
      <button class="weui-btn"  @click="addOrder" type="primary" plain="true">确定提交</button>
    </div>


  
  </view>
</view>
</template>

<script>
import api from "@/utils/api";
import util from "@/utils/util";
import { mapState, mapMutations } from "vuex";
import wx from "wx";
import getCurrentPages from "wxFunction";
import user from "@/services/user";
import QQMapWX from "@/utils/map";

var qqmapsdk;
qqmapsdk = new QQMapWX({
  //key: "SQLBZ-NKX3U-VU4VL-2NPHC-JSAEV-4AFFZ"
  key: "DHNBZ-2ZLKK-T7IJJ-AXSQW-WX5L6-A6FJZ"
});

var app = getApp();

export default {
  computed: {
    ...mapState(["cityName"])
  },
  data() {
    return {
      location,
      orderContent: "",
      latitude: "",
      longitude: "",
      address: "",
      showMap: true,
      loginAttr: true,
      lookMe: true,
      loginReletion: true,
      canIUse: wx.canIUse("button.open-type.getUserInfo"),
      mapImag: ""
    };
  },
  onShow() {
    console.log("onShow ");
    let userInfo = wx.getStorageSync("userInfo");
    let token = wx.getStorageSync("token");
    user
      .checkLogin()
      .then(rres => {
        console.log("checkloginf  login");
      })
      .catch(err => {
        console.log("checkloginf  failure no login", err);
        this.loginAttr = false;
      });
  },
  onLoad() {
    var _this = this;
    _this.lookMe = true;
    console.log("onLoad 当前page----------------");
    let userInfo = wx.getStorageSync("userInfo");
    let token = wx.getStorageSync("token");
    user
      .checkLogin()
      .then(rres => {
        console.log("checkloginf  login");
      })
      .catch(err => {
        console.log("checkloginf  failure no login", err);
        _this.loginAttr = false;
        _this.loginReletion = false;
      });
 Object.assign(this.$data, this.$options.data());
    // console.log("msg:i am comming ")
    // wx.getSetting({
    //   success(res) {
    //     //如果没有同意授权,打开设置
    //     if (!res.authSetting["scope.userLocation"]) {
    //       // console.log("??经授权");
    //       wx.openSetting({
    //         success: res => {
    //           // console.log("??经授权");
    //         }
    //       });
    //     } else {
    //       // console.log("已经授权");
    //       wx.getLocation({
    //         type: "gcj02",
    //         success: res => {
    //           // console.log("已经授权2:" + res.latitude);
    //           qqmapsdk.reverseGeocoder({
    //             location: {
    //               latitude: res.latitude,
    //               longitude: res.longitude
    //             },
    //             success: res => {
    //               // console.log(
    //               //   "已经授权3 " + res.result.formatted_addresses.recommend
    //               // );
    //               _this.location = res.result.formatted_addresses.recommend;
    //             }
    //           });
    //         }
    //       });
    //     }
    //   }
    // });
  },
  async mounted() {
    this.getCityName();
  },
  methods: {
    goLogin() {
      user
        .loginByWeixin()
        .then(res => {
          this.userInfo = res.data.userInfo;
          app.globalData.userInfo = res.data.userInfo;
          app.globalData.token = res.data.token;
          this.loginAttr = true;
          console.log("登陆success");
        })
        .catch(err => {
          console.log("登陆失败", err);
        });
    },
    clieckMe() {
      var _this = this;
      _this.lookMe = false;
    },
    searchAddress() {
      var _this = this;
      wx.chooseLocation({
        success: res => {
          console.log(res.latitude + " res.longitude " + res.longitude);
          console.log(res);
          let latitude = res.latitude;
          let longitude = res.longitude;
          _this.address = res.address;
          //this.location = res.result.formatted_addresses.recommend;
          console.log("searchAddress=" + res);
          qqmapsdk.reverseGeocoder({
            location: {
              latitude: latitude,
              longitude: longitude
            },
            success: res => {
              console.log("searchAddress " + res);
              _this.location = res.address; //result.formatted_addresses.recommend;
              let url =
                "http://api.map.baidu.com/staticimage?width=300&height=200&";
              url = url + "center=" + longitude + "," + latitude;
              url = url + "&zoom=18&markers=" + longitude + "," + latitude;
              url = url + "&markerStyles=l,";
              console.log(url);
              _this.latitude = latitude;
              _this.longitude = longitude;
              _this.showMap = false;
              _this.mapImag = url;
            }
          });
        }
      });
    },
    async addOrder() {
      var _this = this;
      console.log("记得我的下一次：" + this.orderContent);
      console.log("记得我的下一次longitude：" + this.longitude);
      // // 验证订单内容是否填写
      // if (checkedProduct.goods_number < this.number) {
      //   wx.showToast({
      //     image: "/static/images/icon_error.png",
      //     title: "请填写订单详细内容",
      //     mask: true
      //   });
      //   return false;
      // }
      // 添加到购物车 OrderSalesSubmit
      console.log("OrderSalesSubmit ：" + this.latitude);

      console.log("OrderSaleeeeeesSubmit ：");

      const res = await api.OrderSalesSubmit({
        orderContent: this.orderContent,
        longitude: this.longitude,
        latitude: this.latitude,
        address: this.address
      });
      console.log("添加到购物车，请求结果", res);
      if (res.errno === 0) {
        wx.showModal({
          title: "",
          confirmColor: "#b4282d",
          content: "下单成功，等待主管审批,再来一单？",
          success: function(res) {
            if (res.confirm) {
              var page = getCurrentPages();
              console.log("当前page", page);
              _this.latitude = "";
              _this.longitude = "";
              _this.showMap = true;
              _this.mapImag = "";
              _this.orderContent = "";

              page[page.length - 1].onLoad();
            } else {
              wx.switchTab({
                url: "/pages/index/index",
                success: function(e) {
                  // console.log('getCurrentPages的页面栈', getCurrentPages());
                  var page = getCurrentPages().pop();
                  // console.log('当前page', page);
                  if (page === undefined || page === null) return;
                  page.onShow();
                }
              });
            }
          }
        });
        // this.openAttr = !this.openAttr;
        //this.cartGoodsCount = res.data.cartTotal.goodsCount;
      } else {
        wx.showToast({
          image: "/static/images/icon_error.png",
          title: res.errmsg,
          mask: true
        });
      }
    },
    // 减少数量
    cutNumber() {
      this.number = this.number - 1 > 1 ? this.number - 1 : 1;
    },
    // 增加数量
    addNumber() {
      this.number = this.number + 1;
    }
  },

  toMappage() {
    var _this = this;
    // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scope
    wx.getSetting({
      success(res) {
        //如果没有同意授权,打开设置
        if (!res.authSetting["scope.userLocation"]) {
          wx.openSetting({
            success: res => {
              _this.getCityName();
            }
          });
        } else {
          wx.navigateTo({
            url: "/pages/mappage/main"
          });
        }
      }
    });
  },
  getCityName() {
    var _this = this;
    console.log("getCityName");
    var myAmapFun = new amapFile.AMapWX({
      key: "e545e7f79a643f23aef187add14e4548"
    });
    myAmapFun.getRegeo({
      success: function(data) {
        //成功回调
        console.log(data);
        // data[0].regeocodeData.formatted_address
        // _this.cityName = data[0].regeocodeData.formatted_address;
        _this.update({ cityName: data[0].regeocodeData.formatted_address });
      },
      fail: function(info) {
        //失败回调
        console.log(info);
        //如果用户拒绝授权
        // 默认为北京
        _this.cityName = "北京市";
        _this.update({ cityName: "北京市" });
      }
    });
  },
  // 原生的分享功能
  onShareAppMessage: function() {
    return {
      title: "cs28Shop",
      desc: "昌顺28小程序粮油商城",
      path: "/pages/index/index"
    };
  }
};
</script>

<style>
.container {
  background: #f4f4f4;
  height: auto;
  overflow: hidden;
  width: 100%;
  padding-left: 32rpx;
  padding-right: 32rpx;
}
.banner {
  width: 750rpx;
  height: 417rpx;
}

.banner image {
  width: 100%;
  height: 417rpx;
}
</style>
